package numberSix;

import java.util.Random;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Guess {

    private int answer=0;
    private int result=0;

    private int l_r=0;

    private Lock lock=new ReentrantLock();

    private int left=1;
    private int right=100;

    public synchronized void separate(){
        if (this.answer==0){
            this.notifyAll();
            try {
                this.wait();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }else if (this.result==0){
            this.result=(this.left+this.right)/2;
            System.out.println("我猜是"+this.result);
            this.notifyAll();
            try {
                this.wait();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }else if (this.l_r==1){
            this.right=this.result-1;
            this.result=(this.left+this.right)/2;
            System.out.println("我猜是"+this.result);
            this.notifyAll();
            try {
                this.wait();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }else if (this.l_r==-1){
            this.left=this.result+1;
            this.result=(this.left+this.right)/2;
            System.out.println("我猜是"+this.result);
            this.notifyAll();
            try {
                this.wait();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }


    }

    public synchronized void judge(){
        if (this.answer==0){
            this.answer=new Random().nextInt(100)+1;
            this.notifyAll();
            try {
                this.wait();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }else if(this.result==this.answer) {
            System.out.println("猜对了");
            System.exit(0);
        }else if (this.result>this.answer){
            System.out.println("大了");
            this.l_r=1;
            this.notifyAll();
            try {
                this.wait();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }else if (this.result<this.answer){
            System.out.println("小了");
            this.l_r=-1;
            this.notifyAll();
            try {
                this.wait();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
